package com.haimi.shiguang.utils;

import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.haimi.shiguang.framework.GlobalCache;


/**
 * ToastUtil
 */
public class ToastUtil {


    /**
     * Show一个Toast出来.see{@link #showToast(String)}
     *
     * @param stringID int | ResourceID
     */
    public static Toast showToast(int stringID) {
        return showToast(GlobalCache.getContext().getResources().getString(stringID));
    }

    /**
     * showToast
     *
     * @param content String | Toast文案内容
     * @return Toast | 如果在子线程调用这个方法,将会返回一个null
     */
    public static Toast showToast(String content) {
        showToast(content, Toast.LENGTH_SHORT);
        return null;
    }

    public static Toast showToast(String content, int duration) {

        if (Looper.myLooper() != Looper.getMainLooper()) {
            showToastOnMainThread(content);
        } else {
            final Toast toast = Toast.makeText(GlobalCache.getContext(), content, duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return toast;
        }
        return null;
    }

    /**
     * 切换到主线程showToast
     *
     * @param content String
     */
    private static void showToastOnMainThread(final String content) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    showToast(content);
                }
            });
        } else {
            showToast(content);
        }
    }
}
